package com.jdone.compus.service;

import com.jdone.compus.client.HaileIocClient;
import com.jdone.compus.dto.ApiResponse;
import com.jdone.compus.dto.ImeiRecordDto;
import com.jdone.compus.model.ImeiRecord;
import com.jdone.compus.repository.ImeiRecordRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.*;

@Service
@RequiredArgsConstructor
public class ImeiRecordService {

    @Autowired
    private ImeiRecordRepository repository;

    @Autowired
    private HaileIocClient client;

    /**
     * 创建并绑定
     */
    @Transactional
    public ImeiRecord create(ImeiRecord record) {
        record.setIsBind(false);
        ImeiRecord saved = repository.save(record);

        ApiResponse resp = client.bind(
                saved.getImei(),
                String.valueOf(saved.getId()),
                "H030001",
                saved.getName(),
                saved.getLocation(),
                saved.getAddress()
        );

        boolean success = false;
        if (resp.getData() instanceof Map) {
            Map<String, Object> data = (Map<String, Object>) resp.getData();
            String retCode = Objects.toString(data.get("retCode"), "");
            success = "00000".equals(retCode);
        }

        saved.setIsBind(success);
        return repository.save(saved);
    }

    /**
     * 更新（过滤已删除记录）
     */
    public ImeiRecord update(Long id, ImeiRecord dto) {
        ImeiRecord record = repository.findByIdAndIsDeleted(id, 0)
                .orElseThrow(() -> new EntityNotFoundException("记录不存在或已删除: " + id));
        record.setName(dto.getName());
        record.setImei(dto.getImei());
        record.setManufacturer(dto.getManufacturer());
        record.setAddress(dto.getAddress());
        record.setLocation(dto.getLocation());
        return repository.save(record);
    }

    /**
     * 根据ID查询（过滤已删除）
     */
    public ImeiRecord getById(Long id) {
        return repository.findByIdAndIsDeleted(id, 0)
                .orElseThrow(() -> new EntityNotFoundException("记录不存在或已删除: " + id));
    }

    /**
     * 逻辑删除（解绑成功后）
     */
    @Transactional
    public ApiResponse logicalDelete(Long id) {

        ImeiRecord record = repository.findByIdAndIsDeleted(id, 0)
                .orElseThrow(() -> new EntityNotFoundException("记录不存在或已删除: " + id));

        client.unbind(record.getImei());

//        if (resp.getData() instanceof Map) {
//            Map<String, Object> data = (Map<String, Object>) resp.getData();
//            String retCode = Objects.toString(data.get("retCode"), "");
//
//            if ("00000".equals(retCode)) {
//                record.setIsDeleted(1);
//                repository.save(record);
//                return ApiResponse.success("删除成功");
//            } else {
//                String retInfo = Objects.toString(data.get("retInfo"), "");
//                return ApiResponse.error("解绑失败（retCode=" + retCode +
//                        "，retInfo=" + retInfo + "），未删除记录");
//            }
//        }
        record.setIsDeleted(1);
        repository.save(record);
        return ApiResponse.success("删除成功");
    }

    /**
     * 分页查询（过滤已删除）
     */
    public Page<ImeiRecord> list(Pageable pageable) {
        return repository.findByIsDeleted(0, pageable);
    }

    /**
     * 条件分页查询（过滤已删除）
     */
    public Page<ImeiRecord> listByCriteria(ImeiRecordDto dto) {
        Pageable pageable = PageRequest.of(dto.getPage() - 1, dto.getSize(), Sort.by("createdAt").descending());

        Specification<ImeiRecord> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(cb.equal(root.get("isDeleted"), 0)); // 过滤已删除

            if (StringUtils.hasText(dto.getName())) {
                predicates.add(cb.like(root.get("name"), "%" + dto.getName() + "%"));
            }
            if (StringUtils.hasText(dto.getImei())) {
                predicates.add(cb.like(root.get("imei"), "%" + dto.getImei() + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };

        return repository.findAll(spec, pageable);
    }

    /**
     * 关键词模糊查询（过滤已删除）
     */
    public List<ImeiRecord> findAll(String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return repository.findByIsDeleted(0);
        }
        String kw = keyword.trim();
        return repository.findByIsDeletedAndNameContainingOrImeiContaining(0, kw, kw);
    }
}
